package com.frejoys.common.log;

import com.frejoys.common.request.ThreadContext;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 打印请求的参数日志
 */
@Slf4j
@RestControllerAdvice
public class LogTraceRequest implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (ThreadContext.get() != null) {
            log.info("追踪请求 路由:{} traceId:{} 时间:{} 用户:{} ip:{} data:{}", RequestUtil.route(), RequestUtil.traceId(), TimeUtil.unixTime(), RequestUtil.userId(), RequestUtil.ip(), body);
        } else {
            log.info("追踪请求 {}: {}", TimeUtil.unixTime(), body);
        }

        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

}
